package com.cs.store.controller;

import com.cs.common.result.HttpResp;
import com.cs.common.result.ResultCode;
import com.cs.domain.vo.ShopCarVo;
import com.cs.store.service.IOrderService;
import com.cs.store.service.IShopCarService;
import com.cs.tools.util.SnowFlakeUtil;
//import com.cs.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/order")
public class OrderController {


    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IShopCarService iShopCarService;
//    @Autowired
//    private IUserService iUserService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 下单
     * @param username
     * @param storeId
     * @param payPrice
     * @return
     */
    @PutMapping("submitOrder")
    public HttpResp submitOrder(String username, Long storeId,String payPrice) {

        List<ShopCarVo> shopCarsvo = iShopCarService.findCar(username, storeId);
        if (shopCarsvo.size() == 0) {//判断购物车是否有商品，如果没有商品，下单失败。
            return HttpResp.result(ResultCode.ORDER_ADD_ERROR, new Date(), null);
        } else {
            //雪花id
            String orderNum = SnowFlakeUtil.snowflakeIdStr();
            StringBuilder sb = new StringBuilder(orderNum + "");
            String orderNo = sb.substring(6, 18);//留12位

            /**
             * 存入订单信息
             */
                    String val = username + ":ORDERINFO|" + orderNo; //val值拼的userid+订单号
            stringRedisTemplate.opsForValue().set("order_" + orderNo, val, 1, TimeUnit.MINUTES); //设置key的有效时间

            iOrderService.payOrder(username, storeId, orderNo,payPrice);    //购物车商品存入订单表设置待支付状态
//            stringRedisTemplate.opsForValue().set("order_" + orderNo, val, 15, TimeUnit.MINUTES); //设置key的有效时间
            return HttpResp.result(ResultCode.ORDER_ADD_SUCCESS, new Date(), orderNo);//返回下单成功，获得订单号
        }
    }

    /**
     * 取消订单
     * @param orderNo
     * @return
     */
    @GetMapping("Cancel")
    public HttpResp Cancel(String orderNo) {
        iOrderService.updateOrder("已取消",orderNo);
        //订单从缓存中删除
        return HttpResp.result(ResultCode.USER_ORDER_CANCEL, new Date(), stringRedisTemplate.delete("order_" + orderNo));
    }

    /**
     * 订单倒计时
     * @param orderNo
     * @return
     */
    @GetMapping("overTime")
    public HttpResp overTime(String orderNo) {

        Long overtime =  stringRedisTemplate.getExpire("order_"+orderNo);
        return HttpResp.result(ResultCode.OVERTIME_SUCCESS, new Date(), overtime);
    }

}
